'use strict';

angular.module('app').controller('createDeviceController', ['$scope', '$rootScope', '$state', '$timeout', 'toaster', '$modal',
	function($scope, $rootScope, $state, $timeout, toaster, $modal) {
		$scope.record = {
			status:'0',
			isIntegratedVideo:'0',
			locationType:1,
			id:$state.params.id,
			deviceClass:1
		};
		if($state.includes('**.update')) {
			$scope.title = "修改设备信息";
			$scope.loading = true;
			$scope.reset = false;//修改不允许重置，因为关联太多的数据，重置后数据很可能丢失
			var id = $state.params.id;
			activate(id);
			validate();
		} else if($state.includes('**.create')) {
			$scope.title = "新增设备";
			$scope.reset = true;//新增时可以重置
			$("#A0").attr("checked", true);
			$("#A1").attr("checked", true);
			validate();
		}
		
		//重置表单
		$scope.resetFrom = function(){
			$scope.record = {
				status:'0',
				isIntegratedVideo:'0',
				locationType:1,
				id:$state.params.id,
				deviceClass:1
			};
		}
		// 新增、修改
		$scope.submit = function() {
			$scope.record.ability = [];
			var abilityInput = $('input[type="checkbox"]');
			for(var i= 0 ;i<abilityInput.length;i++){
				if($(abilityInput[i]).is(':checked')){
					// console.log($(abilityInput[i]).attr('data-code'));
					$scope.record.ability.push($(abilityInput[i]).attr('data-code'));
				}else{
					continue;
				}
			}
			var m = $scope.record;
			console.log(m);
			if($scope.record.id != null) { //id非空代表着是修改
				if(m) {
					
					$scope.isDisabled = true;
					$.ajax({
						type: 'POST',
						dataType: 'json',
						contentType: 'application/json;charset=UTF-8',
						url: '/dac/dm/dmManager/update',
						data: angular.toJson($scope.record)
					}).then(function(result){
						if(result.httpCode == 200) { // 成功
						toaster.clear('*');
						toaster.pop('success', '', "保存成功");
						$timeout(function() {

							$state.go("main.dm.dmManager.list");
						}, 2000);
					} else {
						toaster.clear('*');
						toaster.pop('error', '', result.msg);
						$scope.isDisabled = false;
					}
					});
				}

			} else { //id为空代表着是新增
				if(m) {
					$scope.isDisabled = true;
					$.ajax({
						type: 'POST',
						dataType: 'json',
						contentType: 'application/json;charset=UTF-8',
						url: '/dac/dm/dmManager/create',
						data: angular.toJson($scope.record)
					}).then(function(result){
						if(result.httpCode == 200) { // 成功
							toaster.clear('*');
							toaster.pop('success', '', "保存成功");
							$timeout(function() {
	
								$state.go("main.dm.dmManager.list");
							}, 2000);
						} else {
							toaster.clear('*');
							toaster.pop('error', '', result.msg);
							$scope.isDisabled = false;
						}
					});
				}
			}

		}

		// 初始化页面
		function activate(id) {
			$.ajax({
				type: 'PUT',
				dataType: 'json',
				contentType: 'application/json;charset=UTF-8',
				url: '/dac/dm/dmManager/deviceInfo',
				data: angular.toJson({
					'id': id
				})
			}).then(function(result) {
				console.log(result);
				$scope.loading = false;
				if(result.httpCode == 200) {
					$scope.record = result.data;
					if($scope.record.isIntegratedVideo!=='1'){
						$scope.record.isIntegratedVideo='0'
					}
					$scope.record.id = id; // 给id值，因为后台需要根据是否有id值来操作：新增（无id）或者修改（有id）
					$scope.record.status = $scope.record.status + ''; // 解决修改页面无法回显status值的问题
					
					var abilities = $scope.record.abilities;
					var arr = [];
					arr = abilities.split(",");
					var abilityInput = $('input[type="checkbox"]');
					
						for (var j = 0; j < arr.length; j++) {
							if($(abilityInput[arr[j]]).attr('data-code')==arr[j]){
								$("#A"+arr[j]+"").attr("checked", true);
							}
						}
						
										} else {
					$scope.msg = result.msg;
				}
				$scope.$apply();
			});
		}

		// 表单校验
		function validate() {
			jQuery('form').validate({
				rules: {
					deviceCode: {
						required: true
					},
					houseName: {
						required: true
					},
					deviceName: {
						required: true
					},
					categoryName: {
						required: true
					},
					status: {
						required: true
					},
					productName: {
						required: true
					}
				},
				messages: {
					deviceCode: {
						required: '请输入设备编码'
					},
					houseName: {
						required: '请输入房屋名称'
					},
					deviceName: {
						required: '请输入设备名称'
					},
					categoryName: {
						required: '请输入类型名称'
					},
					status: {
						required: '请选择状态'
					},
					productName: {
						required: '请选择产品名称'
					}
				},
				submitHandler: function() {
					$scope.submit();
				}
			});
		}
		
		//设备产品模态框
		$scope.openProducts = function() {
			var modalInstance = $modal.open({
				templateUrl: 'productList.html', // script标签中定义的id
				controller: 'productModalCtrl', // modal对应的Controller
				size: 'lg',
				resolve: {
					items: function() {
						return $scope.items;
					}
				}
			});

			modalInstance.opened.then(function() { // 模态窗口打开之后执行的函数

			});
			modalInstance.result.then(function(result) {
				$scope.record.productId = result[0];
				$scope.record.productName = result[1];
				$scope.record.registerCode = result[2];
				$scope.record.masterApikey = result[3];
			},function(reason) {
				console.log(reason);
			});
		};

		// 房屋地址模态框
		$scope.openDmBuilding = function() {
			var modalInstance = $modal.open({
				templateUrl: 'dmHouseList.html', // script标签中定义的id
				controller: 'dmHouseModalCtrl', // modal对应的Controller
				size: 'lg',
				resolve: {
					items: function() {
						return $scope.items;
					}
				}
			});

			modalInstance.opened.then(function() { // 模态窗口打开之后执行的函数

			});
			modalInstance.result.then(function(result) {
				console.log(result);
				if(result){
					$scope.record.houseId= result[0];
					$scope.record.houseName = result[1];
					$scope.record.address = result[2];

				}
				
			}, function(reason) {
				console.log(reason);
			})
		};
		
		// 设备类型模态框
		$scope.openCategory = function() {
			var modalInstance = $modal.open({
				templateUrl: 'categoryList.html', // script标签中定义的id
				controller: 'categoryModalCtrl', // modal对应的Controller
				size: 'lg',
				resolve: {
					items: function() {
						return $scope.items;
					}
				}
			});

			modalInstance.opened.then(function() { // 模态窗口打开之后执行的函数

			});
			modalInstance.result.then(function(result) {

				$scope.record['categoryId'] = result[0];
				$scope.record['categoryName'] = result[1];
			}, function(reason) {
				console.log(reason);
			});

		};
	}
]);

// 设备产品模态框
app.controller('productModalCtrl', function($scope, $rootScope, $modal, $modalInstance, items) {
	$scope.param = {};
	$scope.search = function() {
		$scope.loading = true;
		if($scope.pageFlag != 1) { //未点击翻页
			$scope.param.pageNum = 1; //将页码设置为1，即跳转回第一页
		} else { //点击翻页
			$scope.pageFlag = 2; //将开关值设置为2
		}
		$.ajax({
			type: 'PUT',
			dataType: 'json',
			contentType: 'application/json;charset=UTF-8',
			url: '/dac/dm/product/list',
			data: angular.toJson($scope.param)
		}).then(function(result) {
			$scope.loading = false;
			if(result.httpCode == 200) {
				$scope.pageInfo = result;
			} else {
				$scope.msg = result.msg;
			}
			$scope.$apply();
		});
	}
	$scope.search();

	$scope.selectProduct = function(items) {
		$scope.params = [];
		$scope.params[0] = items.productId;
		$scope.params[1] = items.productName;
		$scope.params[2] = items.registerCode;
		$scope.params[3] = items.masterApikey;
		$modalInstance.close($scope.params);
	};
	$scope.cancel = function() {
		$modalInstance.dismiss('cancel');
	};

	// 翻页
	$scope.pagination = function(page) {
		$scope.param.pageNum = page;
		$scope.pageFlag = 1; //将开关值设置为1
		$scope.search();
	};
});

//楼栋模态框
app.controller('dmHouseModalCtrl', function($scope, $rootScope, $modal, $modalInstance, items) {
	$scope.param = {};
	$scope.search = function() {
		$scope.loading = true;
		if($scope.pageFlag != 1) { //未点击翻页
			$scope.param.pageNum = 1; //将页码设置为1，即跳转回第一页
		} else { //点击翻页
			$scope.pageFlag = 2; //将开关值设置为2
		}
		$scope.param.status = 1;
		$.ajax({
			type: 'PUT',
			dataType: 'json',
			contentType: 'application/json;charset=UTF-8',
			url: '/dac/bm/building/list',
			data: angular.toJson($scope.param)
		}).then(function(result) {
			$scope.loading = false;
			if(result.httpCode == 200) {
				$scope.pageInfo = result;
			} else {
				$scope.msg = result.msg;
			}
			$scope.$apply();
		});
	}
	$scope.search();

	$scope.selectDmBuilding = function(buildingid, buildingname, buildingaddress, status) {
		$scope.params = [];
		$scope.params[0] = buildingid;
		$scope.params[1] = buildingname;
		$scope.params[2] = buildingaddress;
		$modalInstance.close($scope.params);
	};
	$scope.cancel = function() {
		$modalInstance.dismiss('cancel');
	};

	// 翻页
	$scope.pagination = function(page) {
		$scope.param.pageNum = page;
		$scope.pageFlag = 1; //将开关值设置为1
		$scope.search();
	};
});

// 设备类型模态框
app.controller('categoryModalCtrl', function($scope, $rootScope, $modal, $modalInstance, items) {
	$scope.param = {};
	$scope.search = function() {
		$scope.loading = true;
		if($scope.pageFlag != 1) { //未点击翻页
			$scope.param.pageNum = 1; //将页码设置为1，即跳转回第一页
		} else { //点击翻页
			$scope.pageFlag = 2; //将开关值设置为2
		}
		$.ajax({
			type: 'POST',
			dataType: 'json',
			contentType: 'application/json;charset=UTF-8',
			url: '/dac/dm/category/list',
			data: angular.toJson($scope.param)
		}).then(function(result) {
			$scope.loading = false;
			if(result.httpCode == 200) {
				$scope.pageInfo = result;
			} else {
				$scope.msg = result.msg;
			}
			$scope.$apply();
		});
	}

	$scope.search();

	$scope.selectCategory = function(categoryId, categoryName) {
		$scope.params = [];
		$scope.params[0] = categoryId;
		$scope.params[1] = categoryName;
		$modalInstance.close($scope.params);
	};
	$scope.cancel = function() {
		$modalInstance.dismiss('cancel');
	};
	// 翻页
	$scope.pagination = function(page) {
		$scope.param.pageNum = page;
		$scope.pageFlag = 1; //将开关值设置为1
		$scope.search();
	};
});